package cn.com.dreamtouch.magicbox_general_ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;

import java.io.File;
import java.util.List;

import cn.com.dreamtouch.common.activity.BaseCompatActivity;
import cn.com.dreamtouch.common.util.IntentHelper;
import cn.com.dreamtouch.magicbox_common.util.AppOnForegroundReceiver;
import cn.com.dreamtouch.magicbox_general_ui.R;
import cn.com.dreamtouch.magicbox_general_ui.ui.LoadingProgressDialog;
import cn.com.dreamtouch.magicbox_general_ui.util.MyLogger;
import cn.com.dreamtouch.magicbox_general_ui.view.CenterTitleActionbar;

import static android.os.Process.killProcess;

/**
 * Created by MuHan on 16/7/21.
 */
public class MBBaseActivity extends BaseCompatActivity {
    private AlertDialog mAlertDialog;
    protected MyLogger mLogger;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //页面都竖屏模式
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isActive) {
        //app 从后台唤醒，进入前台
        isActive = true;
            AppOnForegroundReceiver.sendBroadcast(this,isActive);
        }



    }

    @Override
    protected void onPause() {
        super.onPause();
        mLogger.e("onPause");
    }

    /**
     * Hide alert dialog if any.
     */
    @Override
    protected void onStop() {
        super.onStop();
        if (mAlertDialog != null && mAlertDialog.isShowing()) {
            mAlertDialog.dismiss();
        }
        if (!isAppOnForeground()) {
            //app 进入后台
            isActive = false;
            AppOnForegroundReceiver.sendBroadcast(this,isActive);
            //全局变量isActive = false 记录当前已经进入后台
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭加载提示
        hideLoadingProgress();
    }

    public void initActionBar(CenterTitleActionbar centerTitleActionbar) {
        setSupportActionBar(centerTitleActionbar.getToolbar());//toolbar赋予actionbar属性
        centerTitleActionbar.setTitle(this.getTitle().toString());//设置自定义标题
        getSupportActionBar().setDisplayShowTitleEnabled(false);//设置不显示默认标题
    }
    @Override
    protected boolean onNavigation() {
            return true;
    }

    @Override
    public void onBackPressed() {
        if (isTaskRoot())
            IntentHelper.backMain(this);//切换只后台的退出
        else
            super.onBackPressed();

    }

    @Override
    protected void initVariables() {
          mLogger = MyLogger.kLog();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

    }

    @Override
    protected void loadData() {

    }
    //用于接口调用时提示加载中
    //LoadingProgressDialog mBaseProgressDialog;
    ProgressDialog mBaseProgressDialog;
    public void showLoadingProgress() {
        try {
            if (mBaseProgressDialog == null || !mBaseProgressDialog.isShowing()) {
                 // mBaseProgressDialog = LoadingProgressDialog.show(this, false,null);
                mBaseProgressDialog = ProgressDialog.show(this, "", "请稍候...", false);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
                                                                                                                                                                                                                                                                                                                                                                                                               }

    public void hideLoadingProgress() {
        try {
            if (mBaseProgressDialog != null && mBaseProgressDialog.isShowing()) {
                mBaseProgressDialog.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
    public static final int REQUEST_STORAGE_WRITE_ACCESS_PERMISSION = 102;
    public static final int REQUEST_CAMERA_ACCESS_PERMISSION = 104;
    public static final int REQUEST_STORAGE_READ_ACCESS_FOR_CROP_PERMISSION = 103;
    /**
     * Requests given permission.
     * If the permission has been denied previously, a Dialog will prompt the user to grant the
     * permission, otherwise it is requested directly.
     */
    public void requestPermission(final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            showAlertDialog( rationale,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(MBBaseActivity.this,
                                    new String[]{permission}, requestCode);
                        }
                    }, getString(R.string.label_ok), null, getString(R.string.label_cancel));
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }
    /**
     * This method shows dialog with given title & message.
     * Also there is an option to pass onClickListener for positive & negative button.
     *
     * @param message                       - dialog message
     * @param onPositiveButtonClickListener - listener for positive button
     * @param positiveText                  - positive button text
     * @param onNegativeButtonClickListener - listener for negative button
     * @param negativeText                  - negative button text
     */
    public void showAlertDialog(@Nullable String message,
                                @Nullable DialogInterface.OnClickListener onPositiveButtonClickListener,
                                @NonNull String positiveText,
                                @Nullable DialogInterface.OnClickListener onNegativeButtonClickListener,
                                @NonNull String negativeText) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.app_name_magicbox));
        builder.setMessage(message);
        builder.setPositiveButton(positiveText, onPositiveButtonClickListener);
        builder.setNegativeButton(negativeText, onNegativeButtonClickListener);
        mAlertDialog = builder.show();
    }
    /**
     * 不可取消的选择框
     * This method shows dialog with given title & message.
     * Also there is an option to pass onClickListener for positive & negative button.
     *
     * @param message                       - dialog message
     * @param onPositiveButtonClickListener - listener for positive button
     * @param positiveText                  - positive button text
     * @param onNegativeButtonClickListener - listener for negative button
     * @param negativeText                  - negative button text
     */
    public void showAlertDialogNoCancel(@Nullable String message,
                                @Nullable DialogInterface.OnClickListener onPositiveButtonClickListener,
                                @NonNull String positiveText,
                                @Nullable DialogInterface.OnClickListener onNegativeButtonClickListener,
                                @NonNull String negativeText) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.app_name_magicbox));
        builder.setMessage(message);
        builder.setPositiveButton(positiveText, onPositiveButtonClickListener);
        builder.setNegativeButton(negativeText, onNegativeButtonClickListener);
        builder.setCancelable(false);
        mAlertDialog = builder.show();
    }
    private static final String IMAGE_UNSPECIFIED = "image/*";
    protected static final int ALBUM_REQUEST_CODE = 2;//选相册
    protected static final int CAMERA_REQUEST_CODE = 1;//选拍照

    /**
     * 用于拍照照片保存路径
     * @return
     */
    protected String getImageFolder()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                    getString(R.string.permission_read_storage_rationale),
                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
        }
        String imageFolder = Environment.getExternalStorageDirectory() + "/jjs/";
        File imageFolderFile =new File(imageFolder);
        if (!imageFolderFile.exists()) {
            imageFolderFile.mkdirs();
        }
        return imageFolder;
    }
    /**
     * 调用相机
     */
    protected void showCamera(String targetPath) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.CAMERA,
                    getString(R.string.permission_camera_rationale),
                    REQUEST_CAMERA_ACCESS_PERMISSION);
        }
        else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
           requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
             getString(R.string.permission_read_storage_rationale),
                   REQUEST_STORAGE_READ_ACCESS_FOR_CROP_PERMISSION);
        }
        else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(targetPath)));

            intent.putExtra("outputFormat",
                    Bitmap.CompressFormat.JPEG.toString());
            startActivityForResult(intent, CAMERA_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_CAMERA_ACCESS_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
                        && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                            getString(R.string.permission_read_storage_rationale),
                            REQUEST_STORAGE_READ_ACCESS_FOR_CROP_PERMISSION);
                }

            }
        }else {
            super.onRequestPermissionsResult(requestCode,permissions,grantResults);
        }
    }

    /**
     * 调用相册
     */
    protected void pickFromGallery() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                    getString(R.string.permission_read_storage_rationale),
                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
        } else {
            Intent intent = new Intent();
            intent.setType(IMAGE_UNSPECIFIED);
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(Intent.createChooser(intent, getString(R.string.info_choose_from_album)), ALBUM_REQUEST_CODE);
        }
    }




    /**
     * 给接口更新成功后工作调用使用
     */
    public void updateNextWork(){

    }

    public void showSimpleDialog(String msg) {
        new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.app_name_magicbox))
                .setMessage(msg)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .show();
    }
    /**
     * 关闭app对话框
     */
    protected void showFinishDialog(String msg) {
        new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.app_name_magicbox))
                .setCancelable(false)
                .setMessage(msg)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        killProcess(android.os.Process.myPid());    //获取PID
                        System.exit(0);   //常规java、c#的标准退出法，返回值为0代表正常退出
                    }
                })
                .show();
    }
     static boolean isActive;

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public boolean isAppOnForeground() {
        // Returns a list of application processes that are running on the
        // device

        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }
    public void goToAtivity(Class clazz, Bundle bundle) {
        Intent it = new Intent(this, clazz);
        if (bundle != null) {
            it.putExtra("bundle", bundle);
        }
        startActivity(it);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }
    public void jump2ActivityForResult(Class<? extends Activity> activity, int requestCode, String... extras) {
        if (extras.length % 2 != 0) {
            return;
        }
        Intent intent = new Intent(this, activity);
        for (int i = 0; i < extras.length; i++) {
            intent.putExtra(extras[i], extras[++i]);
        }
//        stopLoadingView();
        startActivityForResult(intent, requestCode);
    }

}
